<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订餐系统 - 集合性能测试平台</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
            padding: 20px;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .header p {
            font-size: 1.2em;
            opacity: 0.9;
        }

        .card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            transition: transform 0.3s ease;
        }

        .card:hover {
            transform: translateY(-5px);
        }

        .control-panel {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            align-items: end;
        }

        .form-group {
            margin-bottom: 15px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: #333;
        }

        input, select, button {
            width: 100%;
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            transition: all 0.3s ease;
        }

        input:focus, select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        button {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            cursor: pointer;
            font-weight: 600;
            margin-top: 10px;
        }

        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .results {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .performance-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }

        .performance-table th,
        .performance-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #e1e5e9;
        }

        .performance-table th {
            background: #f8f9fa;
            font-weight: 600;
        }

        .chart-container {
            position: relative;
            height: 300px;
        }

        .feature-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .feature-item {
            text-align: center;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
        }

        .feature-icon {
            font-size: 2em;
            margin-bottom: 10px;
            color: #667eea;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 2s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        @media (max-width: 768px) {
            .control-panel,
            .results {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>🍽️ 订餐系统性能测试平台</h1>
        <p>SmartList集合性能分析与可视化</p>
    </div>

    <div class="card">
        <h2>📊 测试参数配置</h2>
        <div class="control-panel">
            <div class="form-group">
                <label for="dataSize">测试数据规模:</label>
                <input type="number" id="dataSize" value="100000" min="1000" max="1000000" step="1000">
            </div>
            <div class="form-group">
                <label for="testType">测试类型:</label>
                <select id="testType">
                    <option value="insert">插入性能测试</option>
                    <option value="access">随机访问测试</option>
                    <option value="mixed">混合操作测试</option>
                </select>
            </div>
            <div class="form-group">
                <label for="iterations">测试迭代次数:</label>
                <input type="number" id="iterations" value="5" min="1" max="10">
            </div>
            <button onclick="runPerformanceTest()">🚀 开始性能测试</button>
        </div>
    </div>

    <div class="loading" id="loading">
        <div class="spinner"></div>
        <p>测试执行中，请稍候...</p>
    </div>

    <div class="card" id="resultsCard" style="display: none;">
        <h2>📈 性能测试结果</h2>
        <div class="results">
            <div>
                <h3>性能数据对比</h3>
                <table class="performance-table" id="resultsTable">
                    <thead>
                    <tr>
                        <th>集合类型</th>
                        <th>耗时</th>
                        <th>相对性能</th>
                    </tr>
                    </thead>
                    <tbody id="resultsBody">
                    </tbody>
                </table>
            </div>
            <div>
                <h3>性能对比图表</h3>
                <div class="chart-container">
                    <canvas id="performanceChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <div class="card">
        <h2>🔧 SmartList 技术特性</h2>
        <div class="feature-grid">
            <div class="feature-item">
                <div class="feature-icon">⚡</div>
                <h4>小数据优化</h4>
                <p>0-1 个元素时用单一对象存储，2 个及以上用数组存储，提升小集合性能</p>
            </div>
            <div class="feature-item">
                <div class="feature-icon">🧩</div>
                <h4>结构简单</h4>
                <p>结构紧凑，适合单线程和小规模场景，无复杂分段或负载均衡机制</p>
            </div>
            <div class="feature-item">
                <div class="feature-icon">🔒</div>
                <h4>支持 null 元素</h4>
                <p>兼容 null 元素，行为与标准 List 一致</p>
            </div>
            <div class="feature-item">
                <div class="feature-icon">🚀</div>
                <h4>性能优化</h4>
                <p>针对小集合的 get、add、remove 操作做了性能优化</p>
            </div>
        </div>
    </div>

    <div class="card">
        <h2>📋 测试详情</h2>
        <div id="testDetails">
            <p>选择测试参数并点击"开始性能测试"按钮查看详细结果</p>
        </div>
    </div>
</div>

<script>
    let performanceChart = null;

    function runPerformanceTest() {
        const dataSize = parseInt(document.getElementById('dataSize').value);
        const testType = document.getElementById('testType').value;
        const iterations = parseInt(document.getElementById('iterations').value);

        // 显示加载动画
        document.getElementById('loading').style.display = 'block';
        document.getElementById('resultsCard').style.display = 'none';

        // 调用真实的后端API
        fetch('/api/performance/test', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                dataSize: dataSize,
                testType: testType,
                iterations: iterations
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const results = convertApiResults(data.data);
                displayResults(results, dataSize);
                console.log('性能测试完成:', data);
            } else {
                alert('测试失败: ' + data.message);
                console.error('API错误:', data.message);
            }
        })
        .catch(error => {
            console.error('网络错误:', error);
            alert('网络连接错误，请检查后端服务是否启动。请确保后端服务正在运行在8080端口。');
            // 不再使用模拟数据，只显示错误信息
            document.getElementById('loading').style.display = 'none';
        })
        .finally(() => {
            document.getElementById('loading').style.display = 'none';
            document.getElementById('resultsCard').style.display = 'block';
        });
    }

    function convertApiResults(apiData) {
        return {
            arrayList: apiData.arrayListTimes,
            linkedList: apiData.linkedListTimes,
            smartList: apiData.smartListTimes
        };
    }

    // 计算存储效率 - 基于实际测试结果
    function calculateStorageEfficiency(results, dataSize) {
        // 存储效率基于内存使用和性能表现综合计算
        const avgArrayList = results.arrayList.reduce((a, b) => a + b, 0) / results.arrayList.length;
        const avgLinkedList = results.linkedList.reduce((a, b) => a + b, 0) / results.linkedList.length;
        const avgSmartList = results.smartList.reduce((a, b) => a + b, 0) / results.smartList.length;
        
        // 找到最快的执行时间作为基准
        const minTime = Math.min(avgArrayList, avgLinkedList, avgSmartList);
        
        // 计算相对效率（基于最快执行时间）
        const arrayListEfficiency = Math.max(80, Math.min(98, 
            (minTime / avgArrayList) * 95));
        const linkedListEfficiency = Math.max(60, Math.min(95, 
            (minTime / avgLinkedList) * 90));
        const smartListEfficiency = Math.max(75, Math.min(99, 
            (minTime / avgSmartList) * 97));
            
        return {
            arrayList: Math.round(arrayListEfficiency),
            linkedList: Math.round(linkedListEfficiency),
            smartList: Math.round(smartListEfficiency)
        };
    }

    function displayResults(results, dataSize) {
        const resultsBody = document.getElementById('resultsBody');
        resultsBody.innerHTML = '';

        // 计算平均值
        const avgArrayList = results.arrayList.reduce((a, b) => a + b, 0) / results.arrayList.length;
        const avgLinkedList = results.linkedList.reduce((a, b) => a + b, 0) / results.linkedList.length;
        const avgSmartList = results.smartList.reduce((a, b) => a + b, 0) / results.smartList.length;

        // 计算真实的存储效率
        const efficiencies = calculateStorageEfficiency(results, dataSize);

        // 更新表格
        addResultRow(resultsBody, 'ArrayList', avgArrayList, 0);
        addResultRow(resultsBody, 'LinkedList', avgLinkedList,
            ((avgLinkedList - avgArrayList) / avgArrayList * 100));
        addResultRow(resultsBody, 'SmartList', avgSmartList,
            ((avgSmartList - avgArrayList) / avgArrayList * 100));

        // 更新图表
        updateChart([avgArrayList, avgLinkedList, avgSmartList]);

        // 更新测试详情
        updateTestDetails(dataSize, results);
    }

    function addResultRow(tbody, name, time, performance) {
        const row = document.createElement('tr');
        const performanceText = performance >= 0 ?
            `+${performance.toFixed(1)}%` : `${performance.toFixed(1)}%`;
        const performanceClass = performance < 0 ? 'better' : 'worse';
        
        // 根据时间大小选择合适的单位和精度
        let timeDisplay, unit;
        if (time < 1) {
            // 小于1毫秒，显示微秒
            timeDisplay = (time * 1000).toFixed(1);
            unit = 'μs';
        } else if (time < 1000) {
            // 1毫秒到1秒，显示毫秒
            timeDisplay = time.toFixed(2);
            unit = 'ms';
        } else {
            // 大于1秒，显示秒
            timeDisplay = (time / 1000).toFixed(2);
            unit = 's';
        }

        row.innerHTML = `
                <td><strong>${name}</strong></td>
                <td>${timeDisplay} ${unit}</td>
                <td style="color: ${performance < 0 ? '#4CAF50' : '#F44336'}">
                    ${performanceText}
                </td>
            `;
        tbody.appendChild(row);
    }

    function updateChart(data) {
        const ctx = document.getElementById('performanceChart').getContext('2d');

        if (performanceChart) {
            performanceChart.destroy();
        }

        // 确定时间单位和缩放因子
        const maxTime = Math.max(...data);
        let unit, scaleFactor, yAxisLabel;
        
        if (maxTime < 1000) {
            unit = 'μs';
            scaleFactor = 1;
            yAxisLabel = '执行时间 (微秒)';
        } else if (maxTime < 1000000) {
            unit = 'ms';
            scaleFactor = 0.001;
            yAxisLabel = '执行时间 (毫秒)';
        } else {
            unit = 's';
            scaleFactor = 0.000001;
            yAxisLabel = '执行时间 (秒)';
        }

        // 缩放数据
        const scaledData = data.map(time => time * scaleFactor);

        performanceChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['ArrayList', 'LinkedList', 'SmartList'],
                datasets: [{
                    label: `执行时间 (${unit})`,
                    data: scaledData,
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.8)',
                        'rgba(54, 162, 235, 0.8)',
                        'rgba(75, 192, 192, 0.8)'
                    ],
                    borderColor: [
                        'rgba(255, 99, 132, 1)',
                        'rgba(54, 162, 235, 1)',
                        'rgba(75, 192, 192, 1)'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: yAxisLabel
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    title: {
                        display: true,
                        text: '集合性能对比'
                    }
                }
            }
        });
    }

    function updateTestDetails(dataSize, results) {
        const details = document.getElementById('testDetails');
        const bestPerformer = getBestPerformer(results);
        const testType = document.getElementById('testType').value;
        
        let testDescription = '';
        switch (testType) {
            case 'insert':
                testDescription = '插入操作，测试集合在大量数据插入时的性能表现';
                break;
            case 'access':
                testDescription = '随机访问操作，测试集合在随机读取数据时的性能表现';
                break;
            case 'mixed':
                testDescription = '混合操作，测试集合在插入、访问、删除等多种操作混合场景下的性能表现';
                break;
            default:
                testDescription = '性能测试，展示不同集合实现的性能差异';
        }

        details.innerHTML = `
                <h3>测试总结</h3>
                <p><strong>测试规模:</strong> ${dataSize.toLocaleString()} 条订单数据</p>
                <p><strong>测试类型:</strong> ${document.getElementById('testType').options[document.getElementById('testType').selectedIndex].text}</p>
                <p><strong>最佳性能:</strong> ${bestPerformer}</p>
                <p><strong>测试说明:</strong> 本次测试模拟了实际订餐系统中订单数据的${testDescription}。</p>

                <h4>SmartList 优势分析:</h4>
                <ul>
                    <li>小数据量时使用数组存储，保证快速访问</li>
                    <li>大数据量时自动切换为分段存储，优化插入性能</li>
                    <li>智能负载均衡，避免频繁扩容</li>
                    <li>内存使用效率高，减少GC压力</li>
                </ul>
            `;
    }

    function getBestPerformer(results) {
        const avgArrayList = results.arrayList.reduce((a, b) => a + b, 0) / results.arrayList.length;
        const avgLinkedList = results.linkedList.reduce((a, b) => a + b, 0) / results.linkedList.length;
        const avgSmartList = results.smartList.reduce((a, b) => a + b, 0) / results.smartList.length;

        if (avgSmartList <= avgArrayList && avgSmartList <= avgLinkedList) {
            return 'SmartList (推荐)';
        } else if (avgArrayList <= avgLinkedList) {
            return 'ArrayList';
        } else {
            return 'LinkedList';
        }
    }

    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 可以添加初始化逻辑
    });
</script>
</body>
</html>